﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;
using YunHao;

namespace UnknowWorld.CardGame
{
    /// <summary>
    /// 特效池
    /// </summary>
    public class EffectPool : MonoBehaviour
    {
        public static EffectPool Instance
        {
            get
            {
                if (!instance)
                    instance = new GameObject("EffectPool", typeof(EffectPool)).GetComponent<EffectPool>();
                return instance;
            }
        }

        private static EffectPool instance;

        void Awake()
        {
            if (!instance)
                instance = this;
        }

        void OnEnable()
        {
            InitEffectPool();
        }

        void OnDisable()
        {
            instance = null;
            _dataPool.Clear();
        }

        #region Load Data

        /// <summary>
        /// 所有特效
        /// </summary>
        public List<CardEffect> Effects
        {
            get
            {
                return _dataPool;
            }
        }

        /// <summary>
        /// 特效池
        /// </summary>
        private List<CardEffect> _dataPool = new List<CardEffect>();

        /// <summary>
        /// 是否加载成功
        /// </summary>
        public bool Loaded
        {
            get
            {
                return _dataLoaded;
            }
        }

        /// <summary>
        /// 特效数据加载是否完成
        /// </summary>
        private bool _dataLoaded;

        /// <summary>
        /// 初始化特效池
        /// </summary>
        void InitEffectPool()
        {
            string effectDir = Path.Combine(Application.streamingAssetsPath, "Effect");
            string effectDataPath = Path.Combine(effectDir, "Effects.dat");
            LoadEffectPool(effectDataPath);
        }

        /// <summary>
        /// 加载本地特效池
        /// </summary>
        /// <param name="path"></param>
        void LoadEffectPool(string path)
        {
            XmlControl.ReadXmlAsync<List<CardEffect>>(path, (effects) =>
            {
                _dataPool.AddRange(effects);
                _dataLoaded = true;
            }, (err) =>
            {
                Debug.LogErrorFormat("Card Load Fail:", err);
            });
        }

        /// <summary>
        /// 通过key获取Effect
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public CardEffect EffectByKey(string key)
        {
            CardEffect effect = null;
            foreach (var et in _dataPool)
            {
                if (et.Key == key)
                {
                    effect = et;
                    break;
                }
            }
            return effect;
        }
        #endregion

        #region Use Effect

        #endregion
    }
}